﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Tezzanator.Net.XNAGUI.Controls
{
    public class BaseControl
    {
        public Vector2 Position;
        public Vector2 Size;
        public string Name;
        public bool Visible = true;

        public List<BaseControl> Children;
        public BaseControl Parent;

        protected Gui gui;
        protected Vector2 AbsoluteScreenPosition;

        public delegate void ControlEventHandler(BaseControl Sender);

        public BaseControl()
        {
            Children = new List<BaseControl>();
            Parent = null;
            Position = Vector2.Zero;
            Size = Vector2.Zero;
        }

        public void SetParent(BaseControl NewParent)
        {
            Parent = NewParent;
        }
        public void SetGui(Gui thegui)
        {
            gui = thegui;
        }

        public void AddChild(BaseControl NewChild)
        {
            Children.Add(NewChild);
            NewChild.SetParent(this);
            NewChild.SetGui(gui);
        }

        public virtual void Draw(GameTime gameTime, SpriteBatch spritebatch )
        {
            if (Visible)
            {
                foreach (BaseControl Child in Children)
                {
                    Child.Draw(gameTime, spritebatch);
                }
            }
        }

        public virtual void Update(GameTime gameTime)
        {
            if (Parent == null)
            {
                AbsoluteScreenPosition = Position;
            }
            else
            {
                AbsoluteScreenPosition = Parent.Position + Position;
            }

            // The Update order is the opposite to the draw order.
            // Because what is infront is what is "hit" first by the mouse...
            if (Visible)
            {
                Children.Reverse();
                foreach (BaseControl Child in Children)
                {
                    Child.Update(gameTime);
                }
                Children.Reverse();
            }
        }
    }
}
